var path = require('path');
var log4js = require(path.resolve(__dirname, '../config/logger'));
var logger = log4js.getLogger('status');
var DbCommon = require('./db');
const Phrase = require('./phrase');
class Paragraph {
  constructor(id) {
    this.id = id;
    this.name = '';
    this.template = '';
    this.phrases = [];
    this.realPhrases = [];
    this.phrasesMap = {};
    this.status = 1;
    this.content = '';
    this.force = false;
    this.data = null;
  }
  init() {
    var that = this;
    return new Promise(function (resolve, reject) {
      let wheres = [{
        type: 1,
        key: 'id',
        value: that.id
      }]
      let sqlOptions = {
        wheres: wheres,
        table: 'paragraph'
      }
      if (that.id) {
        DbCommon.getDataById(sqlOptions).then(function (data) {
          if (data.length > 0) {
            that.name = data[0].name;
            that.status = data[0].status;
            that.template = data[0].template;
            that.phrases = JSON.parse(data[0].template);
            resolve();
          } else {
            reject(new Error('paragraph ' + that.id + 'init no data find'));
          }
        }).catch(function (error) {
          reject(error);
        });
      } else {
        resolve();
      }

    })
  }
  getRealPhrases() {
    if (this.phrases.length > 0) {
      this.phrases.forEach((element) => {
        // 随机取一个phrase
        if (element.type == 2) {
          let length = element.phrases.length;
          let rand = parseInt(length * Math.random(), 10);
          this.realPhrases.push(element.phrases[rand]);
        }
        // 单个
        if (element.type == 1) {
          this.realPhrases.push(element.phrases[0]);
        }
      })
    }
  }
  getContent() {
    var that = this;
    return new Promise(function (resolve, reject) {
      that.init().then(function () {
        that.getRealPhrases();
        let promiseArrs = [];
        let serialRequest = [];
        that.realPhrases.forEach(element => {
          if (!that.phrasesMap[element.id]) {
            let phrase = new Phrase(element.id);
            phrase.setAutoParams(that.autoParams);
            phrase.setForce(that.force);
            that.phrasesMap[element.id] = phrase;
            serialRequest.push(phrase);
            //promiseArrs.push(phrase.getContent())
          }
        });
        let index = 0;
        let length = serialRequest.length;
        // 串行解析段落
        const phraseGo = function() {
          if (index == length) {
            that.getRealContent();
            resolve('ok');
          } else {
            serialRequest[index].getContent().then(function(result) {
              index++;
              phraseGo();
            }).catch(function(error) {
              console.log(error);
              reject(error);
            })
          }
        }
        phraseGo();
        // Promise.all(promiseArrs).then(function (result) {
        //   that.getRealContent();
        //   resolve('ok');
        // }).catch(function (err) {
        //   reject(err);
        // })
      }).catch(function (error) {
        reject(error);
      })
    })

  }
  getRealContent() {
    this.content = '';
    this.realPhrases.forEach(element => {
      if (this.phrasesMap[element.id]) {
        this.content += this.phrasesMap[element.id].content;
      }
    });
  }
  // 传入变动参数
  setAutoParams(autoParams) {
    this.autoParams = autoParams || {};
  }
  setForce(force) {
    this.force = force;
  }
}

module.exports = Paragraph;